﻿using DigitalHealth.PACS.ChatWebSocket.Middleware;
using DigitalHealth.PACS.ChatWebSocket.Services;
using DigitalHealth.PACS.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DigitalHealth.PACS.ChatWebSocket.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize]
    public class ChatUserController : ControllerBase
    {
        private IChatUserServer chatUserServer { get; set; }
        private IChatServer chatServer { get; set; }

        public ChatUserController(IChatUserServer chatUserServer)
        {
            this.chatUserServer = chatUserServer;
        }

        //获取所有用户
        [HttpGet]
        public IEnumerable<ChatUser> Get()
        {
            return chatUserServer.GetChatUsers();
        }

        [HttpGet]
        [Route("{id}")]
        public ChatUser GetById(string id)
        {
            return chatUserServer.GetChatUsersById(id);
        }
        [Route("no/{no}")]
        [HttpGet]
        public ChatUser GetByNo(string no)
        {
            return chatUserServer.GetChatUsersByNo(no);
        }

        [HttpPost]
        public void Post([FromBody] ChatUser chatUser)
        {
            chatUserServer.Update(chatUser);
        }

        // PUT api/<ChatUserController>/5
        [HttpPut]
        public void Put([FromBody] ChatUser chatUser)
        {
            chatUserServer.Create(chatUser);
            foreach (var item in ChatWebSocketMiddleware._sockets)
            {
                try
                {
                    MsgTemplate msgTemplate = new NoticeMessage() { SenderUser = chatUserServer.GetChatUsersById(item.Key), State = Model.Enumeration.MsgState.已读, ChatTime = DateTime.Now, Content = "RefUser", Id = new Guid(), Type = Model.Enumeration.MessageType.事件 };
                    ChatServerContext chatServerContext = new ChatServerContext() { ChatType = Model.Enumeration.ChatType.通知, ChatMessage = msgTemplate };
                    var buffer = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(chatServerContext));
                    var segment = new ArraySegment<byte>(buffer);
                    _= item.Value.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                catch (Exception ex)
                {
                    Console.OutputEncoding = Encoding.UTF8;
                }
            }
        }

        // DELETE api/<ChatUserController>/5
        [HttpDelete]
        public void Delete([FromBody] ChatUser chatUser)
        {
            chatUserServer.Delete(chatUser);
        }
    }
}
